REM (c) ArmAge software (Malcolm Boura), 1995
REM This program is placed in the public domain, subject to the conditions
REM given in the !help file in !Director by Nick Craig-Wood, except the first
REM which applies to me, not Nick!

REM this program is primarily for use with !Director but may have wider application

REM Syntax: AppEnsure <name> <command>
REM <name> that may be registered with task manager
REM <command> to execute if <name> not is found

REM it would be useful to add an optional automatic iconbar click
REM but that will require more thought

REM ON ERROR PRINT "AppEnsure: "; REPORT$; " at line "; ERL/10: END
ON ERROR: ON ERROR OFF: ERROR EXT ERR,"AppEnsure: "+REPORT$: REM +" at "+STR$ERL

DIM buffer 256

SYS "OS_GetEnv" TO string
string$ = FNstring_c(string)
i = INSTR(string$, """")
i = INSTR(string$, """", i+1)
string$ = FNstring_strip(MID$(string$, i+1))

REM find the task name
i = 1
task$ = FNstring_commandItem(string$, i)
IF task$ = "" ERROR 0, "AppEnsure: No application given so pointless"

REM find the command to run
com$ = FNstring_commandItem(string$, i)
IF com$ = "" ERROR 0, "AppEnsure: No command given so pointless"

r0 = 0
count = 0
REPEAT
  SYS "TaskManager_EnumerateTasks", r0, buffer, 16 TO r0
  IF FNstring_c(buffer!4) = task$ THEN count += 1
UNTIL r0 <= 0

IF count = 0 THEN OSCLI com$
END

DEF FNstring_commandItem(string$, RETURN i)
LOCAL item$, j
i = FNstring_skip(string$, " ", i)
IF MID$(string$, i, 1) = """" THEN
  j = INSTR(string$, """", i+1)
  WHILE MID$(string$, j+1, 1) = """"
    j = INSTR(string$, """", j+2)
  ENDWHILE
  IF j = 0 ERROR 0, "Mismatched quotes"
  item$ = MID$(string$, i+1, j-i-1)
  i = j+1
ELSE
  item$ = FNstring_token(string$, " ", i)
ENDIF
= item$

DEF FNstring_skip(string$, skip$, from%)
WHILE MID$(string$, from%, 1) = skip$
  from% += 1
ENDWHILE
= from%

DEF FNstring_strip(a$)
REM 1.0 16/6/91
WHILE LEFT$(a$,1)=" "
   a$=MID$(a$,2)
   ENDWHILE
WHILE RIGHT$(a$,1)=" "
   a$=LEFT$(a$,LEN a$-1)
   ENDWHILE
=a$

DEF FNstring_token(string$, token$, RETURN i%)
REM 2/3/93
LOCAL p%, a$
IF i% = -1 THEN =""
IF i% = 0 THEN i% = 1
p% = INSTR(string$, token$, i%)
IF p% = 0 THEN
  a$ = MID$(string$, i%)
  i% = -1
ELSE
  a$ = MID$(string$, i%, p%-i%)
  i% = p% + 1
ENDIF
= FNstring_strip(a$)

DEF FNstring_c(p%)
REM 1.0 16/6/91
REM return zero terminated string pointed to by p%
LOCAL a$
WHILE ?p% > 31
  a$ = a$ + CHR$ ?p%
  p% += 1
ENDWHILE
= a$
